import os
from importlib import import_module
from types import ModuleType
from typing import List, Optional


def find_sub_module(name: str, path: Optional[str] = os.path.curdir) -> ModuleType:
    """找寻根目录或者一级子目录下的python脚本

    Args:
        name (str): [description]

    Returns:
        ModuleType: [description]
    """
    module_path = None
    fs = os.listdir(path)
    key = name + ".py"
    for f in fs:
        if f == key:
            module_path = name
            break

        dirpath = os.path.join(path, f)
        if not os.path.isdir(dirpath):
            continue
        for sf in os.listdir(dirpath):
            if sf == key:
                module_path = "%s.%s" % (f, name)
                break

    if module_path is None:
        return None

    return import_module(module_path)


def list_files(path: str, recursive: Optional[bool] = True, file_only: Optional[bool] = True, excludes: Optional[List[str]] = None) -> List[str]:
    """找寻目录（及子目录）下所有文件（和文件夹）

    Args:
        path (str): 找寻路径
        recursive (bool, optional): 是否要查询子目录（递归查找），默认为True
        file_only (bool, optional): 是否只要文件（不要文件夹），默认为True
        excludes (List[str], optional): 不需要包含的文件夹/文件，默认为空

    Returns:
        List[str]: [description]
    """
    if os.path.isfile(path):
        return [path]

    files = []
    file_list = os.listdir(path)
    for file in file_list:
        cur_path = os.path.join(path, file)

        if excludes is not None and file in excludes:
            continue

        if os.path.isdir(cur_path):
            if not file_only:
                files.append(cur_path)
            if recursive:
                files.extend(list_files(cur_path, recursive, file_only, excludes))
        elif os.path.isfile(cur_path):
            files.append(cur_path)

    return files
